
package com.hxrk.cecardvr;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.ViewGroup;
import android.widget.Button;

import java.util.List;

public class MainActivity extends Activity {
    private static final String TAG = "MainActivity";
    private int param = 1;

    private SurfaceView m_prevewview;
    private SurfaceHolder m_surfaceHolder;

    private Button btn0, btn2, btn3, btn4, btn5;

    // 预览开始时间
    private long prevewviewStartTime = 0;

    // 开启预览多长时间后关闭
    private static long prevewviewTime = 1000 * 60 * 1;

    private static final int MSG_DISABLE_PREVIEW = 0;
    private static final int MSG_UPDATE_UI = 1;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case MSG_DISABLE_PREVIEW:
                    setSurfaceView1px();
                    MainActivity.this.finish();
                    break;
                case MSG_UPDATE_UI :
                    updateui();
                    mHandler.sendEmptyMessage(MSG_UPDATE_UI);
                    break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogUtils.i(TAG, "onCreate called.");

        setContentView(R.layout.activity_main);

    }

    /**
     * 判断某个界面是否在前台
     *
     * @param activity 要判断的Activity
     * @return 是否在前台显示
     */
    public static boolean isForeground(Activity activity) {
        return isForeground(activity, activity.getClass().getName());
    }

    /**
     * 判断某个界面是否在前台
     *
     * @param context   Context
     * @param className 界面的类名
     * @return 是否在前台显示
     */
    public static boolean isForeground(Context context, String className) {
        if (context == null || TextUtils.isEmpty(className))
            return false;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (className.equals(cpn.getClassName()))
                return true;
        }
        return false;
    }

    public void updateui() {
        Rect destRect = new Rect();
        Rect srcRect = new Rect();
        // 绘制图像
        Canvas canvas = null;
        if (isForeground(this) && m_surfaceHolder != null)
            canvas = m_surfaceHolder.lockCanvas();
        else
            setSurfaceView1px();

        try {
            int cols = 2, rows = 1;
            int colsub = m_prevewview.getWidth() / cols;
            int rowsub = m_prevewview.getHeight() / rows;
            float bmpW, bmpH, destW, destH, srcW, srcH;
            int index = 0;
            for (int i = 0; i < CamService.CamNumber; i++) {
                if (CamService.camParameters[i].DEV_TYPE == CamParameter.DEV_TYPE_MIPI ||
                                (CamService.camParameters[i].IMG_TYPE == CamParameter.FMT_TYPE_H264 && CamService.camParameters[i].DEV_TYPE == CamParameter.DEV_TYPE_USB)) {
                    //CamService.camParameters[i].videoread();
                    if (canvas != null) {
                        destRect.set(index % cols * colsub, index / cols * rowsub, (index % cols + 1) * colsub, (index / cols + 1) * rowsub);
                        bmpW = CamService.camParameters[i].IMG_WIDTH;
                        bmpH = CamService.camParameters[i].IMG_HEIGHT;
                        destW = destRect.width();
                        destH = destRect.height();
                        if ((destW / bmpW) > (destH / bmpH)) {
                            srcH = destH;
                            srcW = destH / bmpH * bmpW;
                        } else {
                            srcW = destW;
                            srcH = destW / bmpW * bmpH;
                        }
                        srcRect.set(destRect.left + (destRect.width() - (int) srcW) / 2, destRect.top + (destRect.height() - (int) srcH) / 2, destRect.right - (destRect.width() - (int) srcW) / 2, destRect.bottom - (destRect.height() - (int) srcH) / 2);
                        if (CamService.camParameters[i].DEV_TYPE == CamParameter.DEV_TYPE_MIPI) {
                            MyApplication.mPrevewviewCam.setX(srcRect.left);
                            MyApplication.mPrevewviewCam.setY(srcRect.top);
                            ViewGroup.LayoutParams para1 = MyApplication.mPrevewviewCam.getLayoutParams();
                            para1.height = srcRect.height();
                            para1.width = srcRect.width();
                            MyApplication.mPrevewviewCam.setLayoutParams(para1);
                        } else {
                            synchronized (CamService.camParameters[i].bmpsyn) {
                                if (CamService.camParameters[i].bmp != null)
                                    canvas.drawBitmap(CamService.camParameters[i].bmp, null, srcRect, null);
                            }
                        }
                    }
                    index++;
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        if (canvas != null && m_surfaceHolder != null)
            m_surfaceHolder.unlockCanvasAndPost(canvas);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        setSurfaceView1px();
    }

    public void setSurfaceView1px(){
        mHandler.removeMessages(MSG_UPDATE_UI);
        try {
            ViewGroup.LayoutParams para1 = MyApplication.mPrevewviewCam.getLayoutParams();
            para1.height = 1;
            para1.width = 1;
            MyApplication.mPrevewviewCam.setLayoutParams(para1);
            // 有可能在执行完onPause或onStop后,系统资源紧张将Activity杀死,所以有必要在此保存持久数据
            MyApplication.g_Previewstatus = 0;
        }catch (Exception e){
            LogUtils.e(TAG, "setSurfaceView1px错误!!!!!!!");
        }
    }

    // Activity创建或者从后台重新回到前台时被调用
    @Override
    protected void onStart() {
        super.onStart();
        LogUtils.i(TAG, "onStart called.");
    }

    // Activity从后台重新回到前台时被调用
    @Override
    protected void onRestart() {
        super.onRestart();
        LogUtils.i(TAG, "onRestart called.");
    }

    // Activity创建或者从被覆盖、后台重新回到前台时被调用
    @Override
    protected void onResume() {
        super.onResume();
        LogUtils.i(TAG, "onResume called.");

        m_prevewview = (SurfaceView) findViewById(R.id.SurfaceViewPlay);
        m_surfaceHolder = m_prevewview.getHolder(); // 绑定SurfaceView，取得SurfaceHolder对象
        prevewviewStartTime = System.currentTimeMillis();
        MyApplication.g_Previewstatus = 1;
        mHandler.sendEmptyMessageDelayed(MSG_DISABLE_PREVIEW,prevewviewTime);
        mHandler.sendEmptyMessageDelayed(MSG_UPDATE_UI,100);

    }

    @Override
    protected void onStop() {
        super.onStop();
        LogUtils.i(TAG, "onDestory called.");
        setSurfaceView1px();
        prevewviewStartTime = 0;
    }


    /**
     * Activity被系统杀死时被调用. 例如:屏幕方向改变时,Activity被销毁再重建;当前Activity处于后台,系统资源紧张将其杀死.
     * 另外,当跳转到其他Activity或者按Home键回到主屏时该方法也会被调用,系统是为了保存当前View组件的状态. 在onPause之前被调用.
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putInt("param", param);
        LogUtils.i(TAG, "onSaveInstanceState called.put param: " + param);
        super.onSaveInstanceState(outState);
    }

    /**
     * Activity被系统杀死后再重建时被调用.
     * 例如:屏幕方向改变时,Activity被销毁再重建;当前Activity处于后台,系统资源紧张将其杀死,用户又启动该Activity.
     * 这两种情况下onRestoreInstanceState都会被调用,在onStart之后.
     */
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        param = savedInstanceState.getInt("param");
        LogUtils.i(TAG, "onRestoreInstanceState called. get param: " + param);
        super.onRestoreInstanceState(savedInstanceState);
    }
}
